package com.heima.behavior.service.impl;
import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.behavior.entity.ApBehaviorEntry;
import com.heima.behavior.mapper.ApBehaviorEntryMapper;
import com.heima.behavior.service.IApBehaviorEntryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * <p>
 * APP行为实体表,一个行为实体可能是用户或者设备，或者其它 服务实现类
 * </p>
 *
 * @author lj
 * @since 2022-07-05
 */
@Service
public class ApBehaviorEntryServiceImpl extends ServiceImpl<ApBehaviorEntryMapper, ApBehaviorEntry> implements IApBehaviorEntryService {

    /**
     * 通过用户id或设备id获取行为实体对象
     * @param userId
     * @param equipmentId
     * @return
     */
    @Override
    public ApBehaviorEntry getEntryByUserIdOrEquipmentId(Integer userId, String equipmentId) {
        LambdaQueryWrapper<ApBehaviorEntry> queryWrapper = new LambdaQueryWrapper<>();
        // 判断用户是否登录
        if (userId==0) {
            // 游客，设备号
            queryWrapper.eq(ApBehaviorEntry::getEntryId,equipmentId);
        }else {
            // 登录用户，用户id
            queryWrapper.eq(ApBehaviorEntry::getEntryId,userId.toString());
        }
        ApBehaviorEntry entry = this.getOne(queryWrapper);
        // 判断用户行为实体是否存在
        if (entry==null) {
            entry = new ApBehaviorEntry();
            // entry.setId(0);
            if (userId==0) {
                entry.setType(0);
                entry.setEntryId(equipmentId);
            }else {
                entry.setType(1);
                entry.setEntryId(userId.toString());
            }
            entry.setCreatedTime(new Date());
            this.save(entry);
        }
        return entry;
    }
}
